/*
 * Created on 28.06.2006.
 */
package esdomaci.gui;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import esdomaci.io.ObradaPreseta;
import esdomaci.io.Preset;
import esdomaci.io.PresetCollection;

/**
 * @author Milan Aleksic, milanaleksic@gmail.com
 */
public class DijalogIzbora extends JDialog {
    
    private static final long serialVersionUID = 1L;
    private JPanel jContentPane = null;
    private JPanel kontrolniPanel = null;
    private JPanel listaPanel = null;
    private JPanel listaKomandePanel = null;
    private JPanel unosPanel = null;
    private JPanel primeriPanel = null;
    private JButton dugmeOk = null;
    private JButton dugmeRandom = null;
    private JButton dugmeOdustani = null;
    private JButton dugmeDodaj = null;
	private JButton dugmeIzbrisi = null;
	private JButton dugmeIzmeni = null;
    private JComboBox listaPreseta = null;
        
    private JTextField igracX;
    private JTextField igracY;
    private JTextField zlatoX;
    private JTextField zlatoY;
    private JTextField kanibalX;
    private JTextField kanibalY;
    private JTextField rupa1X;
    private JTextField rupa1Y;
    private JTextField rupa2X;
    private JTextField rupa2Y;
    
    private Preset[] preseti;
    
    private Runnable applyThread;
    
    private boolean pripremljenSpisak = false;
    
    public DijalogIzbora(Runnable applyThread) {
        super();
        this.ucitajStarePresete(); // vremenski zahtevna operacija
        this.applyThread = applyThread;
        this.setModal(true);
		this.setTitle("Изаберите подешавања симулатора");
		this.setSize(500, 330);
		this.setResizable(false);
		this.setLocation(150,150);
		this.setContentPane(getJContentPane());
		this.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
		this.addWindowListener( new WindowAdapter() {
			
			@Override
			public void windowActivated(WindowEvent e) {
				if (!pripremljenSpisak) {
					pripremljenSpisak = true;
					resetovanjeListePreseta();
				}
				super.windowActivated(e);
			}

			@Override
			public void windowDeactivated(WindowEvent e) {
				snimiTrenutnePresete();
				super.windowDeactivated(e);
			}
			
		});
    }
    
    protected void ucitajStarePresete() {
    	// prvo kreiramo JAXP utility klasu
    	ObradaPreseta obrada = new ObradaPreseta("zapamceno.xml");
    	
		try {
			obrada.ucitaj();
			
			// nakon uspesnog citanja iz datoteke vrsi se
			// ekstrakcija kolekcije
			PresetCollection kolekcija = obrada.getKolekcija();
			
			// sada iz kolekcije samo iscupamo nase presete:
			
			this.preseti = kolekcija.getPresets();
			
		} catch (Exception e) {
			System.err.println("Doslo je do greske prilikom ucitavanja starih pozicija!");
			e.printStackTrace();
		}
		
	}

    private void resetovanjeListePreseta() {
    	listaPreseta.removeAllItems();
    	listaPreseta.addItem("Пример 0 - почетно");
        for (int i = 1; i< preseti.length; i++)
            listaPreseta.addItem("Пример "+i);
        procitajPreset(0);
	}

	protected void snimiTrenutnePresete() {
    	//sada listu preseta postavljamo u namenski kontejner
    	PresetCollection kolekcija = new PresetCollection();
    	kolekcija.setPresets(preseti);
    	
    	//sada kontejner postavljamo u utility klasu koja se koristi 
    	//za rad sa JAXP-om
    	ObradaPreseta obrada = new ObradaPreseta("zapamceno.xml");
    	obrada.setKolekcija(kolekcija);
    	
		try {
			obrada.snimi();
		} catch (Exception e) {
			System.err.println("Doslo je do greske prilikom snimanja podesavanja!");
			e.printStackTrace();
		}
    }
    
    public void postavi(Point igrac, Point zlato, Point kanibal, Point rupa1, Point rupa2) {
        igracX.setText(String.valueOf(igrac.x+1));
        igracY.setText(String.valueOf(igrac.y+1));        
        zlatoX.setText(String.valueOf(zlato.x+1));
        zlatoY.setText(String.valueOf(zlato.y+1));        
        kanibalX.setText(String.valueOf(kanibal.x+1));
        kanibalY.setText(String.valueOf(kanibal.y+1));        
        rupa1X.setText(String.valueOf(rupa1.x+1));
        rupa1Y.setText(String.valueOf(rupa1.y+1));        
        rupa2X.setText(String.valueOf(rupa2.x+1));
        rupa2Y.setText(String.valueOf(rupa2.y+1));
    }
    
	private javax.swing.JPanel getJContentPane() {
		if(jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(new BorderLayout());
			jContentPane.add(getUnosPanel(), BorderLayout.CENTER);
			jContentPane.add(getPrimeriPanel(), BorderLayout.NORTH);
			jContentPane.add(getKontrolniPanel(), BorderLayout.SOUTH);
			jContentPane.add(new JLabel("      "), BorderLayout.EAST);
		}
		return jContentPane;
	}
	
	private JPanel getListaPanel() {
	    if (listaPanel==null){
	    	listaPanel = new JPanel();
	    	JLabel tmp;
	    	listaPanel.setLayout(new FlowLayout());
	    	listaPanel.add(tmp = new JLabel("Спремни примери:"));
	        tmp.setHorizontalAlignment(JLabel.RIGHT);
	        listaPanel.add(listaPreseta = getListuPreseta());
	    }
	    return listaPanel;
	}
	
	private JButton getDugmeDodaj() {
		if (dugmeDodaj == null){
			dugmeDodaj = new JButton("Додај тренутно листи");
			dugmeDodaj.addActionListener(new ActionListener() {
		           public void actionPerformed(ActionEvent e) {
		        	   Preset[] noviPreseti = new Preset[preseti.length+1];
		        	   for (int i=0; i< preseti.length; i++)
		        		   noviPreseti[i] = preseti[i];
		        	   
		        	   Preset novPreset = new Preset();
		        	   novPreset.setXIgrac(Integer.valueOf(igracX.getText()));
		        	   novPreset.setYIgrac(Integer.valueOf(igracY.getText()));
		        	   novPreset.setXZlato(Integer.valueOf(zlatoX.getText()));
		        	   novPreset.setYZlato(Integer.valueOf(zlatoY.getText()));
		        	   novPreset.setXKanibal(Integer.valueOf(kanibalX.getText()));
		        	   novPreset.setYKanibal(Integer.valueOf(kanibalY.getText()));
		        	   novPreset.setXRupa1(Integer.valueOf(rupa1X.getText()));
		        	   novPreset.setYRupa1(Integer.valueOf(rupa1Y.getText()));
		        	   novPreset.setXRupa2(Integer.valueOf(rupa2X.getText()));
		        	   novPreset.setYRupa2(Integer.valueOf(rupa2Y.getText()));
		        	   
		        	   noviPreseti[noviPreseti.length-1] = novPreset;
		        	   
		        	   preseti = noviPreseti;
		        	   
		        	   resetovanjeListePreseta();  
		           }
			});
		}
		return dugmeDodaj;
	}
	
	private JButton getDugmeIzmeni() {
		if (dugmeIzmeni == null){
			dugmeIzmeni = new JButton("Измени пример");
			dugmeIzmeni.addActionListener(new ActionListener() {
		           public void actionPerformed(ActionEvent e) {
		        	   	int selInd = listaPreseta.getSelectedIndex();
		        	   	preseti[selInd].setXIgrac(Integer.valueOf(igracX.getText()));
		        	   	preseti[selInd].setYIgrac(Integer.valueOf(igracY.getText()));
		        	   	preseti[selInd].setXZlato(Integer.valueOf(zlatoX.getText()));
		        	   	preseti[selInd].setYZlato(Integer.valueOf(zlatoY.getText()));
		        	   	preseti[selInd].setXKanibal(Integer.valueOf(kanibalX.getText()));
		        	   	preseti[selInd].setYKanibal(Integer.valueOf(kanibalY.getText()));
		        	   	preseti[selInd].setXRupa1(Integer.valueOf(rupa1X.getText()));
		        	   	preseti[selInd].setYRupa1(Integer.valueOf(rupa1Y.getText()));
		        	   	preseti[selInd].setXRupa2(Integer.valueOf(rupa2X.getText()));
		        	   	preseti[selInd].setYRupa2(Integer.valueOf(rupa2Y.getText()));
		           }
			});
		}
		return dugmeIzmeni;
	}

	private JButton getDugmeIzbrisi() {
		if (dugmeIzbrisi == null){
			dugmeIzbrisi = new JButton("Избриши овај пример");
			dugmeIzbrisi.addActionListener(new ActionListener() {
		           public void actionPerformed(ActionEvent e) {
		        	   Preset[] noviPreseti = new Preset[preseti.length-1];
		        	   int selInd = listaPreseta.getSelectedIndex();
		        	   for (int i=0; i< selInd; i++)
		        		   noviPreseti[i] = preseti[i];
		        	   
		        	   for (int i=selInd+1; i< preseti.length; i++)
		        		   noviPreseti[i-1] = preseti[i];
		        	   
		        	   preseti = noviPreseti;
		        	   
		        	   resetovanjeListePreseta();
		           }
			});
		}
		return dugmeIzbrisi;
	}
	
	private JPanel getListaKomandePanel() {
	    if (listaKomandePanel==null){
	    	listaKomandePanel = new JPanel();
	    	listaKomandePanel.setLayout(new FlowLayout());	        
	    	listaKomandePanel.add(getDugmeDodaj());
	    	listaKomandePanel.add(getDugmeIzbrisi());
	    	listaKomandePanel.add(getDugmeIzmeni());
	    }
	    return listaKomandePanel;
	}

	private JPanel getPrimeriPanel() {
		if (primeriPanel==null) {
			primeriPanel = new JPanel();
			primeriPanel.setLayout(new BorderLayout());	        
	        primeriPanel.add(getListaPanel(), BorderLayout.NORTH);       
	        primeriPanel.add(getListaKomandePanel(), BorderLayout.CENTER);
		}
		return primeriPanel;
	}
	
	private JPanel getUnosPanel() {
	    if (unosPanel==null) {
	        unosPanel = new JPanel();
	        unosPanel.setLayout(new GridLayout(7, 3, 5, 5));
	        JLabel tmp;
	        	        
	        unosPanel.add(new JLabel(""));
	        unosPanel.add(tmp = new JLabel("X"));
	        tmp.setHorizontalAlignment(JLabel.CENTER);
	        unosPanel.add(tmp = new JLabel("Y"));
	        tmp.setHorizontalAlignment(JLabel.CENTER);
	        
	        unosPanel.add(tmp = new JLabel("Играч:"));
	        tmp.setHorizontalAlignment(JLabel.RIGHT);
	        unosPanel.add(igracX = new JTextField());
	        unosPanel.add(igracY = new JTextField());
	        
	        unosPanel.add(tmp = new JLabel("Злато:"));
	        tmp.setHorizontalAlignment(JLabel.RIGHT);
	        unosPanel.add(zlatoX = new JTextField());
	        unosPanel.add(zlatoY = new JTextField());
	        
	        unosPanel.add(tmp = new JLabel("Канибал:"));
	        tmp.setHorizontalAlignment(JLabel.RIGHT);
	        unosPanel.add(kanibalX = new JTextField());
	        unosPanel.add(kanibalY = new JTextField());
	        
	        unosPanel.add(tmp = new JLabel("Прва рупа:"));
	        tmp.setHorizontalAlignment(JLabel.RIGHT);
	        unosPanel.add(rupa1X = new JTextField());
	        unosPanel.add(rupa1Y = new JTextField());
	        
	        unosPanel.add(tmp = new JLabel("Друга рупа:"));
	        tmp.setHorizontalAlignment(JLabel.RIGHT);
	        unosPanel.add(rupa2X = new JTextField());
	        unosPanel.add(rupa2Y = new JTextField());
	        
	        unosPanel.add(new JLabel(""));
	        unosPanel.add(new JLabel(""));
	        unosPanel.add(new JLabel(""));

	    }
	    return unosPanel;
	}
	
	private void procitajPreset(int index) {
	    if ((index<0)||(index >= preseti.length))
	        return;
	    igracX.setText(   String.valueOf(preseti[index].getXIgrac()) );
	    igracY.setText(   String.valueOf(preseti[index].getYIgrac()) );
	    zlatoX.setText(   String.valueOf(preseti[index].getXZlato()) );
	    zlatoY.setText(   String.valueOf(preseti[index].getYZlato()) );
	    kanibalX.setText( String.valueOf(preseti[index].getXKanibal()) );
	    kanibalY.setText( String.valueOf(preseti[index].getYKanibal()) );
	    rupa1X.setText(   String.valueOf(preseti[index].getXRupa1()) );
	    rupa1Y.setText(   String.valueOf(preseti[index].getYRupa1()) );
	    rupa2X.setText(   String.valueOf(preseti[index].getXRupa2()) );
	    rupa2Y.setText(   String.valueOf(preseti[index].getYRupa2()) );
	}
	
	private JComboBox getListuPreseta() {
	    if (listaPreseta == null) {
	        listaPreseta = new JComboBox();
	        listaPreseta.addItemListener(new ItemListener() {

				public void itemStateChanged(ItemEvent e) {
					procitajPreset(listaPreseta.getSelectedIndex());
				}
	        	
	        });
	    }
	    return listaPreseta;
	}
	
	private JPanel getKontrolniPanel() {
	    if (kontrolniPanel==null){
	        kontrolniPanel = new JPanel();
	        kontrolniPanel.add(getDugmeOk());
	        kontrolniPanel.add(getDugmeRandom());
	        kontrolniPanel.add(getDugmeOdustani());
	    }
	    return kontrolniPanel;
	}
	
	private int testirajVrednost(String s) throws Exception {
	    int tmp = Integer.parseInt(s);
	    if ((tmp<1)||(tmp>4))
	        throw new Exception();
	    return tmp;
	}
	
	private JButton getDugmeOk() {
	    if (dugmeOk==null){
	        dugmeOk = new JButton("Прихвати подешавања");
	        dugmeOk.addActionListener(new ActionListener() {
	           public void actionPerformed(ActionEvent e) {
	               try {
	                   Point rupa1 = new Point(
	                           testirajVrednost(rupa1X.getText()),
	                           testirajVrednost(rupa1Y.getText()));
	                   Point rupa2 = new Point(
	                           testirajVrednost(rupa2X.getText()),
	                           testirajVrednost(rupa2Y.getText()));
	                   Point kanibal = new Point(
	                           testirajVrednost(kanibalX.getText()),
	                           testirajVrednost(kanibalY.getText()));
	                   Point zlato = new Point(
	                           testirajVrednost(zlatoX.getText()),
	                           testirajVrednost(zlatoY.getText()));
	                   Point igrac = new Point(
	                           testirajVrednost(igracX.getText()),
	                           testirajVrednost(igracY.getText()));
	                   if (rupa1.equals(rupa2))
	                       throw new Exception();
	                   if (rupa1.equals(zlato))
	                       throw new Exception();
	                   if (rupa1.equals(igrac))
	                       throw new Exception();
	                   if (rupa2.equals(zlato))
	                       throw new Exception();
	                   if (rupa2.equals(igrac))
	                       throw new Exception();
	                   if (kanibal.equals(zlato))
	                       throw new Exception();
	                   if (kanibal.equals(igrac))
	                       throw new Exception();
	                   if (zlato.equals(igrac))
	                       throw new Exception();
	               }
	               catch (Exception e2) {
	            	   JOptionPane.showMessageDialog( 
		            		    DijalogIzbora.this, 
		            		    "Нисте правилно подесили параметре - неће бити примењени!", 
		            		    "Грешка !", 
		            		    JOptionPane.ERROR_MESSAGE 
		            		);
	            	  return;
	               }
	               
	               EventQueue.invokeLater(applyThread);
	               
	           }
	        });
	    }
	    return dugmeOk;
	}
	
	private JButton getDugmeRandom() {
	    if (dugmeRandom==null){
	        dugmeRandom = new JButton("Генериши");
	        dugmeRandom.addActionListener(new ActionListener() {
	           public void actionPerformed(ActionEvent e) {
	               
	               int tmpx, tmpy;
	               boolean[][] matrica = new boolean[4][4];
	               
	               // za rupe	               
	               matrica[tmpx=(int) Math.round(Math.random() * 3)]
	                      [tmpy=(int) Math.round(Math.random() * 3)] = true;	               
		           rupa1X.setText(String.valueOf(tmpx+1));
		           rupa1Y.setText(String.valueOf(tmpy+1));
		           do {
		               tmpx = (int) Math.round(Math.random() * 3);
		               tmpy = (int) Math.round(Math.random() * 3);
		           }  while (matrica[tmpx][tmpy]);
		           matrica[tmpx][tmpy] = true;
		           rupa2X.setText(String.valueOf(tmpx+1));
		           rupa2Y.setText(String.valueOf(tmpy+1));
		           
		           // za kanibala - bez provere jer moze biti i na mestu rupe!
	               matrica[tmpx=(int) Math.round(Math.random() * 3)]
		                  [tmpy=(int) Math.round(Math.random() * 3)] = true;
	               matrica[tmpx][tmpy] = true;
		           kanibalX.setText(String.valueOf(tmpx+1));
		           kanibalY.setText(String.valueOf(tmpy+1));

		           // za zlato, ovde mora provera jer mora u praznu celiju
		           do {
		               tmpx = (int) Math.round(Math.random() * 3);
		               tmpy = (int) Math.round(Math.random() * 3);
		           }  while (matrica[tmpx][tmpy]);
		           matrica[tmpx][tmpy] = true;
		           zlatoX.setText(String.valueOf(tmpx+1));
		           zlatoY.setText(String.valueOf(tmpy+1));

		           // za igraca
		           do {
		               tmpx = (int) Math.round(Math.random() * 3);
		               tmpy = (int) Math.round(Math.random() * 3);
		           }  while (matrica[tmpx][tmpy]);
		           igracX.setText(String.valueOf(tmpx+1));
		           igracY.setText(String.valueOf(tmpy+1));
	           }
	        });
	    }
	    return dugmeRandom;
	}
	
	private JButton getDugmeOdustani() {
	    if (dugmeOdustani==null){
	        dugmeOdustani = new JButton("Затвори");
	        dugmeOdustani.addActionListener(new ActionListener() {
	           public void actionPerformed(ActionEvent e) {
	               setVisible(false);
	           }
	        });
	    }
	    return dugmeOdustani;
	}
	
	// kanibal
	public int getKanibalX() {
	    return Integer.valueOf(kanibalX.getText()).intValue()-1;
	}
	
	public int getKanibalY() {
	    return Integer.valueOf(kanibalY.getText()).intValue()-1;
	}
	// rupa 1
	public int getRupa1X() {
	    return Integer.valueOf(rupa1X.getText()).intValue()-1;
	}
	
	public int getRupa1Y() {
	    return Integer.valueOf(rupa1Y.getText()).intValue()-1;
	}
	// rupa 2
	public int getRupa2X() {
	    return Integer.valueOf(rupa2X.getText()).intValue()-1;
	}
	
	public int getRupa2Y() {
	    return Integer.valueOf(rupa2Y.getText()).intValue()-1;
	}
	// igrac
	public int getIgracX() {
	    return Integer.valueOf(igracX.getText()).intValue()-1;
	}
	
	public int getIgracY() {
	    return Integer.valueOf(igracY.getText()).intValue()-1;
	}
	// zlato
	public int getZlatoX() {
	    return Integer.valueOf(zlatoX.getText()).intValue()-1;
	}
	
	public int getZlatoY() {
	    return Integer.valueOf(zlatoY.getText()).intValue()-1;
	}
}
